<template>
  <div>
    <!--面包屑导航-->
    <bread></bread>
    <!--卡片视图-->
    <el-card>
      <!--搜索区域-->
      <el-row :span="14" :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--表格区域-->
      <el-table :data="tableData" border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="changest(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!--编辑-->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="backfill(scope.row)"
            ></el-button>
            <!--删除-->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removefun(scope.row.id)"
            ></el-button>
            <!--权限-->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-star-off"
              @click="jurisdiction(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页模块-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.totals"
      >
      </el-pagination>

      <!--添加用户-->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" @close="resetForm">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑用户-->
      <el-dialog title="编辑用户" :visible.sync="dialogVb" @close="resetForm">
        <el-form :model="backfillts" :rules="rules" ref="ruleForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input
              v-model="backfillts.username"
              disabled
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="backfillts.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="backfillts.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVb = false">取 消</el-button>
          <el-button type="primary" @click="redacts('ruleForm')">确 定</el-button>
        </span>
      </el-dialog>
      <!--权限分配-->
      <el-dialog title="分配角色" :visible.sync="flag" width="30%">
        <p>当前的用户：{{ uname.username }}</p>
        <p>当前的角色： {{ uname.role_name }}</p>
        <p>
          <el-form>
            <el-form-item label="分配新角色：">
              <el-select v-model="lclist">
                <el-option
                  :label="item.roleName"
                  :value="item.id"
                  v-for="item in rolist"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="flag = false">取 消</el-button>
          <el-button type="primary" @click="modify">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import bread from "../bread";
export default {
  components: { bread },
  name: "",
  data() {
    return {
      value: "", //搜索数据
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      totals: 0, //页数
      tableData: [], //列表数据
      dialogVisible: false, //添加用户变量

      rules: {
        //正则
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 1, max: 16, message: "请输入正确的邮箱", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 1, max: 16, message: "请输入正确的手机号", trigger: "blur" },
        ],
      },
      //编辑数据
      backfillts: {},
      dialogVb: false, //编辑用户变量
      flag: false, //权限分配变量

      //权限
      lclist: "",
      rolist: [],
      uname: [],
    };
  },
  mounted() {
    this.getlist();
  },
  methods: {
    //获取基本数据
    async getlist() {
      const { data: res } = await this.$axios.get("users", { params: this.queryInfo });
      // console.log(res);
      this.tableData = res.users;
      this.totals = res.total;
    },

    //权限
    async jurisdiction(obj) {
      // console.log(obj);
      this.flag = true;
      this.uname = obj;
      const res = await this.$axios.get("/roles");
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.rolist = res.data;
      // console.log(this.rolist);
    },

    //权限修改
    async modify() {
      if (this.lclist === "") {
        this.$message.error("请选择");
      } else {
        const res = await this.$axios.put(`users/${this.uname.id}/role`, {
          rid: this.uname.id,
        });
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.lclist = "";
        this.getlist();
        this.flag = false;
      }
    },

    //回填
    backfill(obj) {
      this.backfillts = obj;
      this.dialogVb = true;
    },
    //编辑用户
    redacts(ruleForm) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await this.$axios.put(`users/${this.backfillts.id}`, {
            email: this.backfillts.email,
            mobile: this.backfillts.mobile,
          });
          if (res.meta.status == 200) {
            this.$message.success(res.meta.msg);
            this.dialogVb = false;
            this.getlist();
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //更新状态
    async changest(obj) {
      const res = await this.$axios.put(`users/${obj.id}/state/${obj.mg_state}`);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
      }
      this.getlist();
    },

    //添加用户
    async addUser() {
      this.$refs.ruleForm.validate(async (valid) => {
        console.log(valid);
        if (valid) {
          let res = await this.$axios.post("users", this.ruleForm);
          if (res.meta.status == 201) {
            this.$message.success(res.meta.msg);
            this.getlist();
            this.dialogVisible = false;
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //清空重置数据
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },

    //删除
    removefun(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios.delete(`users/` + id).then((res) => {
            console.log(res);
            if (res.meta.status == 200) {
              this.$message.success(res.meta.msg);
            } else {
              this.$message.error(res.meta.msg);
            }
            this.getlist();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //分页
    handleSizeChange(val) {
      this.queryInfo.pagesize = val; //每页条
      this.getlist();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val; //当前页
      this.getlist();
    },
  },
  computed: {},
  watch: {},
};
</script>

<style lang="scss" scoped></style>
